package com.ncloud.product.service.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ncloud.common.enmus.ResultEnum;
import com.ncloud.common.exception.UserException;
import com.ncloud.product.entity.DiscntComp;
import com.ncloud.product.entity.DiscntCompItem;
import com.ncloud.product.mapper.DiscntCompItemMapper;
import com.ncloud.product.mapper.DiscntCompMapper;
import com.ncloud.product.service.DiscntCompService;

@Service
public class DiscntCompServiceImpl implements DiscntCompService{
	
	@Autowired
	private DiscntCompMapper compMapper;
	@Autowired
	private DiscntCompItemMapper itemMapper;
	
	@Override
	public JSONArray getDiscntCompByDiscnt(JSONObject json) {
		if(!json.containsKey("discntId"))
			throw new UserException(ResultEnum.PARAM_ERROR);
		Long discntId=json.getLong("discntId");
		
		JSONArray array = new JSONArray();
		List<DiscntComp> comps = compMapper.getDiscntComp(discntId);
		for (DiscntComp discntComp : comps) {
			List<DiscntCompItem> items = itemMapper.getCompItemByInstId(discntComp.getCompInstId());
			JSONObject jsonObject = setObjectFromComp(items);
			JSONObject discntObject = JSON.parseObject(JSON.toJSONString(discntComp));
			discntObject.putAll(jsonObject);
			array.add(discntObject);
		}
		
		return array;
	}

	private JSONObject setObjectFromComp(List<DiscntCompItem> comps) {
		JSONObject json = new JSONObject();
		for (DiscntCompItem discntComp : comps) {
			json.put(discntComp.getAttrCode(), discntComp.getAttrValue());
		}
		return json;
	}

	@Override
	public JSONArray getCompCountByDiscnt(Long discntId) {
		List<Map<String,Object>> compCount = compMapper.getCompCountByDiscnt(discntId);
		return JSON.parseArray(JSON.toJSONString(compCount,true));
	}

}
